﻿using Core.FrameWork.Commons.Storage;
using QRCoder;
using System;
using System.Drawing;
using System.IO;
using System.Threading.Tasks;

namespace Core.FrameWork.Commons.Hepler
{
    public class QRCodeHelper
    {
        public static async Task<string> Execute(string str)
        {

            QRCodeGenerator qrGenerator = new QRCoder.QRCodeGenerator();
            //QRCodeGenerator.ECCLevel:纠错能力,Q级：约可纠错25%的数据码字
            QRCodeData qrCodeData = qrGenerator.CreateQrCode(str, QRCodeGenerator.ECCLevel.Q);
            QRCode qrcode = new QRCode(qrCodeData);
            Bitmap qrCodeImage = qrcode.GetGraphic(8, Color.Black, Color.White, null, 15, 6, false);
            var bytes = BitmapToBytes(qrCodeImage);
            string fileName = $"{Guid.NewGuid()}.jpg";
            return await UploadHelp.Execute(bytes, fileName, UploadFileType.Image);
        }
        private static byte[] BitmapToBytes(Bitmap bitmap)
        {
            MemoryStream ms = new MemoryStream();
            bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
            byte[] bytes = ms.GetBuffer();  //byte[]   bytes=   ms.ToArray(); 这两句都可以，至于区别么，下面有解释
            ms.Close();
            return bytes;
        }
    }
}
